import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import {setToken, getToken, canTurnTo, setTitle} from '@/libs/util'
import config from '@/config'

const {homeName} = config

Vue.use(Router)
const router = new Router({
  routes: routes,
  linkActiveClass: 'active',
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {x: 0, y: 0}
    }
  },
  mode: 'hash'
})
const LOGIN_PAGE_NAME = 'login'
 

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({replace: true, name: 'error_401'}) // 无权限，重定向到401页面
}


router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  console.log('ssssssssss', to.name, token)
  if (!token && to.name !== LOGIN_PAGE_NAME && to.name !== 'resetPwd') {
    // 未登录且要跳转的页面不是登录页
    console.log("登录信息已失效，请重新登录！！")
    next({
      name: LOGIN_PAGE_NAME,
      query: {tokenExpired: true}
    })
  } else if (!token && (to.name === LOGIN_PAGE_NAME || to.name === 'resetPwd')) {
    console.log("2")
    // 未登陆且要跳转的页面是登录页或重置密码页面
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    console.log("3")
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
  
    if (store.state.user.hasGetInfo) {
      console.log("3")
      //记录from
      store.commit("setRouterFrom", from.name)
      turnTo(to, store.state.user.accessList, next)
    } else {
      console.log("4")
      store.dispatch('getUserInfo').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
        turnTo(to, user.accessList, next)
      }).catch(() => {
        setToken('')
        console.log("登录信息已失效，请重新登录！")
        next({
          name: 'login',
          query: {tokenExpired: true}
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
  //没有特殊的，则把右边内容scrollTop =0
})

export default router
